package com.p2p.account.dao.impl;

import com.p2p.account.dao.AgentLogDao;
import com.p2p.account.po.AgentLog;
import com.p2p.account.vo.AgentLogCondition;
import com.p2p.account.vo.AgentLogResult;
import com.p2p.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository
public class AgentLogDaoImpl implements AgentLogDao {

    private static final Logger logger = LoggerFactory.getLogger(AgentLogDaoImpl.class);

    @Resource
    private JdbcTemplate jdbcTemplate;


    @Override
    public AgentLogResult selectAgentLog(AgentLogCondition agentLogCondition) {
        String startDate = agentLogCondition.getStartDate();
        String endDate = agentLogCondition.getEndDate();
        String agentCode = agentLogCondition.getAgentCode();
        Integer startRow = agentLogCondition.getStartRow();
        Integer pageSize = agentLogCondition.getPageSize();

        String orderField = agentLogCondition.getOrderField();
        String sortField = agentLogCondition.getSortField();

        RowMapper<AgentLog> rowMapper = new BeanPropertyRowMapper<>(AgentLog.class);
        //根据时间获取当前年月份
        String table = "agent_log";

        String sql1 = "";
        String sql2 = "";
        List<AgentLog> agentLogList = new ArrayList<>();
        Integer size = 0;
        if (!StringUtils.isEmpty(agentCode)) {
            sql1 = "SELECT  *  FROM " + table + " WHERE create_time  BETWEEN ? AND ? AND agent_code = ? ORDER BY " + sortField + " " + orderField + " limit ?,?";
            agentLogList = jdbcTemplate.query(sql1, rowMapper, startDate, endDate, agentCode, startRow, pageSize);
            sql2 = "SELECT  count(*)  FROM " + table + " WHERE create_time  BETWEEN ? AND ? AND agent_code = ? ";
            size = jdbcTemplate.queryForObject(sql2, Integer.class, startDate, endDate, agentCode);
        } else {
            sql1 = "SELECT  *  FROM " + table + "  WHERE  create_time BETWEEN ? AND ?  ORDER BY " + sortField + " " + orderField + " limit ?,?";
            agentLogList = jdbcTemplate.query(sql1, rowMapper, startDate, endDate, startRow, pageSize);
            sql2 = "SELECT  count(*)  FROM " + table + " WHERE create_time  BETWEEN ? AND ? ";
            size = jdbcTemplate.queryForObject(sql2, Integer.class, startDate, endDate);
        }

        AgentLogResult agentLogResult = new AgentLogResult(size, agentLogList);
        return agentLogResult;

    }
}
